package com.ruoyi.project.jxy.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.io.File;
import java.util.*;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import io.swagger.annotations.*;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.jxy.domain.Resource;
import com.ruoyi.project.jxy.service.IResourceService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 资源管理Controller
 *
 * @author ruoyi
 * @date 2020-05-21
 */
@Api("资源管理")
@RestController
@RequestMapping("/jxy/resource")
public class ResourceController extends BaseController {
    @Autowired
    private IResourceService resourceService;
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询资源管理列表
     */
    @PreAuthorize("@ss.hasPermi('jxy:resource:list')")
    @GetMapping("/list")
    @ApiOperation("资源列表")
    public TableDataInfo list(Resource resource) {
        //startPage();
        QueryWrapper<Resource> queryWrapper = new QueryWrapper<Resource>();
        if (StringUtils.isNotBlank(resource.getType())) {
            queryWrapper.eq("type", resource.getType());
        }
        if (resource.getParentId() != null) {
            //parent id 下的文件及文件夹
            queryWrapper.eq("parent_id", resource.getParentId());
        } else {
            //第一级
            queryWrapper.isNull("parent_id");
        }
        queryWrapper.select("id,parent_id,type,region,theme,folder_type,display_name,create_time,create_user,path,IF(folder_type='1','true','false') is_folder");
        List<Resource> list = resourceService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 新增文件夹
     */
    @PreAuthorize("@ss.hasPermi('jxy:resource:addForder')")
    @Log(title = "资源管理(新建文件夹)", businessType = BusinessType.INSERT)
    @PostMapping("addFolder")
    @ApiOperation("新建文件夹")
    public AjaxResult addFolder(@RequestBody Resource resource) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("display_name", resource.getDisplayName());
        queryWrapper.eq("type", resource.getType());
        queryWrapper.eq("folder_type", "1");
        queryWrapper.eq("parent_id", resource.getParentId());
        List<Resource> lst = resourceService.list(queryWrapper);
        if (lst != null && lst.size() > 0) {
            return AjaxResult.error("文件夹名字已存在");
        }
        resource.setFolderType("1");
        resource.setCreateUser(SecurityUtils.getUsername());
        resource.setCreateTime(new Date());
        return toAjax(resourceService.save(resource) ? 1 : 0);
    }

    /**
     * 获取资源管理详细信息
     */
 /*   @PreAuthorize("@ss.hasPermi('jxy:resource:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(resourceService.getById(id));
    }*/

    /**
     * 新增资源管理
     */
    @PreAuthorize("@ss.hasPermi('jxy:resource:add')")
    @Log(title = "资源管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增资源")
    public AjaxResult add(@RequestBody Resource resource) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id", resource.getParentId());
        queryWrapper.eq("display_name", resource.getDisplayName());
        queryWrapper.eq("type", resource.getType());
        Resource tmp = resourceService.getOne(queryWrapper);
        if (tmp != null) {
            String displayName = resource.getDisplayName();
            String date = DateFormatUtils.format(new Date(), DateFormatUtils.ISO_8601_EXTENDED_DATETIME_FORMAT.getPattern());
            displayName = displayName + "_" + date;
            resource.setDisplayName(displayName);
        }
        resource.setCreateUser(SecurityUtils.getUsername());
        resource.setCreateTime(new Date());
        return toAjax(resourceService.save(resource) ? 1 : 0);
    }

    /**
     * 修改资源管理
     */
    @PreAuthorize("@ss.hasPermi('jxy:resource:edit')")
    @Log(title = "资源管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Resource resource) {
        return toAjax(resourceService.updateById(resource) ? 1 : 0);
    }

    /**
     * 删除资源管理
     */
    @PreAuthorize("@ss.hasPermi('jxy:resource:remove')")
    @Log(title = "资源管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(resourceService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
    //获取zip 文件名称
    @GetMapping("/{ids}")
    public AjaxResult getDownloadName(@PathVariable Long[] ids) {
        //选择了下载的
        if (ids != null && ids.length > 0) {
            //创建自定义目录
            String dirName = UUID.randomUUID().toString();
            String dirPath = RuoYiConfig.getProfile() + File.separator + "zip" + File.separator + dirName;
            logger.info("dir path is "+dirPath);
            File dir = FileUtil.mkdir(new File(dirPath));
            for (Long id :
                    ids) {
                createDownloadFile(dirPath, id);
            }
            ZipUtil.zip(dir);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", "/profile/zip/" + dirName + ".zip");
            return ajax;
        }
        return AjaxResult.error("请选择文件");
    }

    private void createDownloadFile(String dirPath, Long parentId) {
        //Resource resource = resourceService.getById(id);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id", parentId);
        List<Resource> resourceList = resourceService.list(queryWrapper);
        if (resourceList != null && resourceList.size() > 0) {
            for (Resource resource :
                    resourceList) {
                //文件夹
                if ("1".equals(resource.getFolderType())) {
                    String tempPath = dirPath + File.separator + resource.getDisplayName();
                    FileUtil.mkdir(tempPath);
                    createDownloadFile(tempPath, resource.getId());
                } else {//文件
                    // 本地资源路径
                    String localPath = RuoYiConfig.getProfile();
                    // 数据库资源地址
                    String downloadPath = localPath + StringUtils.substringAfter(resource.getPath(), Constants.RESOURCE_PREFIX);
                    //拷贝文件到目标目录
                    FileUtil.copy(FileUtil.newFile(downloadPath), FileUtil.newFile(dirPath + File.separator + resource.getDisplayName()), true);
                }
            }
        }

    }
}
